<template>
  <div class="dashboard-container">
    <!-- 标题区域 -->
    <h2 class="panel-title">堆垛机面板</h2>

    <!-- 带左侧滚动条的容器 -->
    <div class="main-scroll-container">
      <!-- 滚动内容区域 -->
      <div class="scroll-content">
        <!-- 核心内容卡片 -->
        <el-card class="monitoring-card">
          <!-- 表格数据展示 -->
          <el-table
            :data="tableData"
            border
            class="monitoring-table"
            :header-cell-class-name="getHeaderClass"
          >
            <el-table-column label="部件名称" prop="axisName" width="120" />
            <el-table-column label="当前位置" prop="ActPosition">
              <template #default="{ row }"
                >{{ row.ActPosition }}{{ row.ActPosition ? ' mm' : '' }}</template
              >
            </el-table-column>
            <el-table-column label="电机转速" prop="ActSpeed">
              <template #default="{ row }"
                >{{ row.ActSpeed }}{{ row.ActSpeed ? ' RPM' : '' }}</template
              >
            </el-table-column>
            <el-table-column label="设定速度" prop="setVelocity">
              <template #default="{ row }"
                >{{ row.setVelocity }}{{ row.setVelocity ? ' 0.1m/min' : '' }}</template
              >
            </el-table-column>
            <el-table-column label="加速度" prop="setAcc">
              <template #default="{ row }"
                >{{ row.setAcc }}{{ row.setAcc ? ' 0.1m/S²' : '' }}</template
              >
            </el-table-column>
            <el-table-column label="减速度" prop="setDec">
              <template #default="{ row }"
                >{{ row.setDec }}{{ row.setDec ? ' 0.1m/S²' : '' }}</template
              >
            </el-table-column>
            <el-table-column label="加、减速度变化率" prop="setAcc_Dec">
              <template #default="{ row }"
                >{{ row.setAcc_Dec }}{{ row.setAcc_Dec ? ' J' : '' }}</template
              >
            </el-table-column>
            <el-table-column label="轴运行信号" prop="axisSignal" />
            <el-table-column label="电机电流" prop="motorCurrent" />
            <el-table-column label="电机扭矩" prop="motorTorque" />
            <el-table-column label="电机温度" prop="motorTem" />
            <el-table-column label="故障代码" prop="faultCode" />
          </el-table>

          <!-- 分隔线 -->
          <div class="separator"></div>

          <!-- 曲线图容器 -->
          <div class="chart-container">
            <div id="telemetryChart" class="chart-wrapper"></div>
          </div>
        </el-card>
      </div>

      <!-- 自定义左侧滚动条 -->
      <div class="custom-scrollbar" ref="scrollbar">
        <div class="scrollbar-thumb" ref="scrollbarThumb"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
  import { ref, onMounted, onUnmounted, nextTick, watchEffect } from 'vue';
  import { ElCard, ElTable, ElTableColumn, ElMessage } from 'element-plus';
  import { useUserStore } from '/@/store/modules/user';
  import { useWebsocketStoreWithOut } from '/@/store/modules/thingsboard/websocket';
  import { getLatestTelemetry } from '/@/api/thingsborad/api/telemetry';
  import * as echarts from 'echarts';

  // 设备配置与状态变量
  const deviceId = '7b25f580-7e64-11f0-a159-f9bfc56b8267';
  const pollingInterval = 1000; // 1秒轮询间隔
  let timer = null;
  const isConnected = ref(false);
  const lastUpdateTime = ref('');

  // 表格数据初始化
  const tableData = ref([
    {
      axisName: 'X轴（行走）',
      ActPosition: '',
      setVelocity: '',
      ActSpeed: '',
      setAcc: '',
      setDec: '',
      setAcc_Dec: '',
      axisSignal: '',
      motorCurrent: '',
      motorTorque: '',
      motorTem: '',
      faultCode: '',
    },
    {
      axisName: 'Y轴（升降）',
      ActPosition: '',
      setVelocity: '',
      ActSpeed: '',
      setAcc: '',
      setDec: '',
      setAcc_Dec: '',
      axisSignal: '',
      motorCurrent: '',
      motorTorque: '',
      motorTem: '',
      faultCode: '',
    },
    {
      axisName: 'Z轴（货叉）',
      ActPosition: '',
      setVelocity: '',
      ActSpeed: '',
      setAcc: '',
      setDec: '',
      setAcc_Dec: '',
      axisSignal: '',
      motorCurrent: '',
      motorTorque: '',
      motorTem: '',
      faultCode: '',
    },
  ]);

  // 历史数据存储（用于曲线图）
  const historyData = ref({
    timeLabels: [], // 时间标签
    x: {
      position: [], // X轴位置
      speed: [], // X轴速度
      setVelocity: [], // X轴设定速度
      acceleration: [], // X轴加速度
      deceleration: [], // X轴减速度
      accDecRate: [], // X轴加减速变化率
      current: [], // X轴电机电流
      torque: [], // X轴电机扭矩
      temperature: [], // X轴电机温度
    },
    y: {
      position: [], // Y轴位置
      speed: [], // Y轴速度
      setVelocity: [], // Y轴设定速度
      acceleration: [], // Y轴加速度
      deceleration: [], // Y轴减速度
      accDecRate: [], // Y轴加减速变化率
      current: [], // Y轴电机电流
      torque: [], // Y轴电机扭矩
      temperature: [], // Y轴电机温度
    },
    z: {
      position: [], // Z轴位置
      speed: [], // Z轴速度
      setVelocity: [], // Z轴设定速度
      acceleration: [], // Z轴加速度
      deceleration: [], // Z轴减速度
      accDecRate: [], // Z轴加减速变化率
      current: [], // Z轴电机电流
      torque: [], // Z轴电机扭矩
      temperature: [], // Z轴电机温度
    },
  });

  // 滚动条相关引用
  const scrollbar = ref(null);
  const scrollbarThumb = ref(null);
  const mainContainer = ref(null);
  const scrollContent = ref(null);

  // 表头样式
  const getHeaderClass = () => 'table-header';

  // 图表实例
  let chartInstance = null;

  // 初始化图表
  const initChart = () => {
    nextTick(() => {
      const chartDom = document.getElementById('telemetryChart');
      if (!chartDom) return;

      chartInstance = echarts.init(chartDom);

      // 图表配置
      const option = {
        title: {
          text: '堆垛机三轴运行数据趋势',
          left: 'center',
          top: 10,
          textStyle: {
            color: 'rgba(255, 255, 255, 0.9)',
            fontSize: 14,
            fontWeight: 'normal',
          },
        },
        tooltip: {
          trigger: 'axis',
          confine: false,
          appendToBody: true,
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: 'rgba(255, 255, 255, 0.5)',
            },
            label: {
              backgroundColor: 'rgba(0, 46, 93, 0.8)',
            },
          },
          padding: 15,
          backgroundColor: 'rgba(0, 20, 40, 0.95)',
          borderColor: 'rgba(255, 255, 255, 0.3)',
          borderWidth: 1,
          textStyle: {
            color: '#fff',
            fontSize: 12,
          },
          formatter: function (params) {
            const vw = window.innerWidth / 100; // 1vw的像素值
            let html = `<div style="margin-bottom: ${0.25 * vw}px; font-weight: bold;">${
              params[0].axisValue
            }</div>`;
            params.forEach((param) => {
              if (param.value !== null && param.value !== undefined) {
                html += `<div style="margin: ${0.15 * vw}px 0;">
                  <span style="display: inline-block; width: ${0.5 * vw}px; height: ${
                  0.5 * vw
                }px; background-color: ${param.color}; margin-right: ${
                  0.4 * vw
                }px; border-radius: ${0.1 * vw}px;"></span>
                  <span style="font-weight: 500;">${param.seriesName}:</span>
                  <span style="float: right; margin-left: ${1 * vw}px; font-weight: bold;">${
                  param.value
                }</span>
                </div>`;
              }
            });
            return html;
          },
        },
        legend: {
          data: [
            // 位置数据
            'X轴位置',
            'Y轴位置',
            'Z轴位置',
            // 速度数据
            'X轴速度',
            'Y轴速度',
            'Z轴速度',
            // 设定速度
            'X轴设定速度',
            'Y轴设定速度',
            'Z轴设定速度',
            // 加速度
            'X轴加速度',
            'Y轴加速度',
            'Z轴加速度',
            // 减速度
            'X轴减速度',
            'Y轴减速度',
            'Z轴减速度',
            // 加减速变化率
            'X轴加减速变化率',
            'Y轴加减速变化率',
            'Z轴加减速变化率',
            // 电机电流
            'X轴电机电流',
            'Y轴电机电流',
            'Z轴电机电流',
            // 电机扭矩
            'X轴电机扭矩',
            'Y轴电机扭矩',
            'Z轴电机扭矩',
            // 温度数据
            'X轴温度',
            'Y轴温度',
            'Z轴温度',
          ],
          textStyle: {
            color: 'rgba(255, 255, 255, 0.8)',
            fontSize: 11,
            fontWeight: 'normal',
          },
          top: 35,
          left: 'center',
          itemWidth: 14,
          itemHeight: 10,
          itemGap: 20,
          type: 'scroll',
          orient: 'horizontal',
          selected: {
            // 默认显示主要数据，隐藏次要数据
            X轴位置: true,
            Y轴位置: true,
            Z轴位置: true,
            X轴速度: true,
            Y轴速度: true,
            Z轴速度: true,
            X轴设定速度: false,
            Y轴设定速度: false,
            Z轴设定速度: false,
            X轴加速度: false,
            Y轴加速度: false,
            Z轴加速度: false,
            X轴减速度: false,
            Y轴减速度: false,
            Z轴减速度: false,
            X轴加减速变化率: false,
            Y轴加减速变化率: false,
            Z轴加减速变化率: false,
            X轴电机电流: false,
            Y轴电机电流: false,
            Z轴电机电流: false,
            X轴电机扭矩: false,
            Y轴电机扭矩: false,
            Z轴电机扭矩: false,
            X轴温度: false,
            Y轴温度: false,
            Z轴温度: false,
          },
        },
        grid: {
          left: '20%',
          right: '20%',
          bottom: '12%',
          top: '32%',
          containLabel: false, // 不自动调整包含标签
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: [],
          axisLine: {
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.3)',
            },
          },
          axisLabel: {
            color: 'rgba(255, 255, 255, 0.7)',
            rotate: 0,
            interval: 2,
            fontSize: 10,
            showMaxLabel: false,
            showMinLabel: false,
            margin: 8,
            formatter: function (value) {
              // 只显示时间，去掉秒数
              return value.split(':').slice(0, 2).join(':');
            },
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.05)',
              type: 'dashed',
            },
          },
          splitNumber: 5,
        },
        yAxis: [
          {
            type: 'value',
            name: '位置/速度',
            nameLocation: 'end',
            nameGap: 17,
            nameTextStyle: {
              color: 'rgba(255, 255, 255, 0.8)',
              fontSize: 11,
              padding: [0, 0, -10, 10],
            },
            axisLine: { lineStyle: { color: 'rgba(255, 255, 255, 0.3)' } },
            axisLabel: {
              color: 'rgba(255, 255, 255, 0.7)',
              fontSize: 9,
              margin: 8,
              formatter: function (value) {
                if (Math.abs(value) >= 1000) {
                  return (value / 1000).toFixed(1) + 'k';
                }
                return value.toFixed(0);
              },
            },
            splitLine: { lineStyle: { color: 'rgba(255, 255, 255, 0.1)' } },
            scale: true,
          },
          {
            type: 'value',
            name: '其他数据',
            position: 'right',
            nameGap: 17,
            show: true,
            nameTextStyle: {
              color: 'rgba(255, 255, 255, 0.8)',
              fontSize: 11,
              padding: [0, 0, -10, -30],
            },
            axisLine: {
              show: true,
              lineStyle: { color: 'rgba(255, 255, 255, 0.3)' },
            },
            axisLabel: {
              show: true,
              color: 'rgba(255, 255, 255, 0.7)',
              fontSize: 9,
              margin: 8,
              formatter: function (value) {
                return value.toFixed(1);
              },
            },
            splitLine: {
              show: true,
              lineStyle: { color: 'rgba(255, 255, 255, 0.05)' },
            },
            scale: true,
            min: function (value) {
              return Math.floor(value.min * 0.9);
            },
            max: function (value) {
              return Math.ceil(value.max * 1.1);
            },
          },
        ],
        series: [
          // 位置数据
          {
            name: 'X轴位置',
            type: 'line',
            data: [],
            smooth: true,
            lineStyle: { color: '#2f89cf', width: 3, type: 'solid' },
            symbol: 'circle',
            symbolSize: 6,
            showSymbol: true,
            emphasis: { scale: true },
            yAxisIndex: 0,
            connectNulls: false,
            sampling: 'lttb',
          },
          {
            name: 'Y轴位置',
            type: 'line',
            data: [],
            smooth: true,
            lineStyle: { color: '#f7ba1e', width: 3, type: 'solid' },
            symbol: 'circle',
            symbolSize: 6,
            showSymbol: true,
            emphasis: { scale: true },
            yAxisIndex: 0,
            connectNulls: false,
            sampling: 'lttb',
          },
          {
            name: 'Z轴位置',
            type: 'line',
            data: [],
            smooth: true,
            lineStyle: { color: '#2dca73', width: 3, type: 'solid' },
            symbol: 'circle',
            symbolSize: 6,
            showSymbol: true,
            emphasis: { scale: true },
            yAxisIndex: 0,
            connectNulls: false,
            sampling: 'lttb',
          },
          // 速度数据
          {
            name: 'X轴速度',
            type: 'line',
            data: [],
            smooth: true,
            lineStyle: { color: '#61a0a8', width: 3, type: 'dashed' },
            symbol: 'triangle',
            symbolSize: 5,
            showSymbol: true,
            emphasis: { scale: true },
            yAxisIndex: 0,
            connectNulls: false,
            sampling: 'lttb',
          },
          {
            name: 'Y轴速度',
            type: 'line',
            data: [],
            smooth: true,
            lineStyle: { color: '#d48265', width: 3, type: 'dashed' },
            symbol: 'triangle',
            symbolSize: 5,
            showSymbol: true,
            emphasis: { scale: true },
            yAxisIndex: 0,
            connectNulls: false,
            sampling: 'lttb',
          },
          {
            name: 'Z轴速度',
            type: 'line',
            data: [],
            smooth: true,
            lineStyle: { color: '#91c7ae', width: 3, type: 'dashed' },
            symbol: 'triangle',
            symbolSize: 5,
            showSymbol: true,
            emphasis: { scale: true },
            yAxisIndex: 0,
            connectNulls: false,
            sampling: 'lttb',
          },
          // 设定速度
          {
            name: 'X轴设定速度',
            type: 'line',
            data: [],
            smooth: false,
            lineStyle: { color: '#61a0a8', width: 2, type: 'solid' },
            symbol: 'circle',
            symbolSize: 4,
            showSymbol: true,
            emphasis: { scale: true },
            yAxisIndex: 0,
          },
          {
            name: 'Y轴设定速度',
            type: 'line',
            data: [],
            smooth: false,
            lineStyle: { color: '#d48265', width: 2, type: 'solid' },
            symbol: 'circle',
            symbolSize: 4,
            showSymbol: true,
            emphasis: { scale: true },
            yAxisIndex: 0,
          },
          {
            name: 'Z轴设定速度',
            type: 'line',
            data: [],
            smooth: false,
            lineStyle: { color: '#91c7ae', width: 2, type: 'solid' },
            symbol: 'circle',
            symbolSize: 4,
            showSymbol: true,
            emphasis: { scale: true },
            yAxisIndex: 0,
          },
          // 加速度
          {
            name: 'X轴加速度',
            type: 'line',
            data: [],
            smooth: false,
            lineStyle: { color: '#ca8622', width: 2, type: 'solid' },
            symbol: 'emptyCircle',
            symbolSize: 6,
            showSymbol: true,
            emphasis: { scale: true },
            yAxisIndex: 1,
          },
          {
            name: 'Y轴加速度',
            type: 'line',
            data: [],
            smooth: false,
            lineStyle: { color: '#bda29a', width: 2, type: 'solid' },
            symbol: 'emptyCircle',
            symbolSize: 6,
            showSymbol: true,
            emphasis: { scale: true },
            yAxisIndex: 1,
          },
          {
            name: 'Z轴加速度',
            type: 'line',
            data: [],
            smooth: false,
            lineStyle: { color: '#6e7074', width: 2, type: 'solid' },
            symbol: 'emptyCircle',
            symbolSize: 6,
            showSymbol: true,
            emphasis: { scale: true },
            yAxisIndex: 1,
          },
          // 减速度
          {
            name: 'X轴减速度',
            type: 'line',
            data: [],
            smooth: false,
            lineStyle: { color: '#ca8622', width: 2, type: 'dashed' },
            symbol: 'emptyCircle',
            symbolSize: 6,
            showSymbol: true,
            emphasis: { scale: true },
            yAxisIndex: 1,
          },
          {
            name: 'Y轴减速度',
            type: 'line',
            data: [],
            smooth: false,
            lineStyle: { color: '#bda29a', width: 2, type: 'dashed' },
            symbol: 'emptyCircle',
            symbolSize: 6,
            showSymbol: true,
            emphasis: { scale: true },
            yAxisIndex: 1,
          },
          {
            name: 'Z轴减速度',
            type: 'line',
            data: [],
            smooth: false,
            lineStyle: { color: '#6e7074', width: 2, type: 'dashed' },
            symbol: 'emptyCircle',
            symbolSize: 6,
            showSymbol: true,
            emphasis: { scale: true },
            yAxisIndex: 1,
          },
          // 加减速变化率
          {
            name: 'X轴加减速变化率',
            type: 'line',
            data: [],
            smooth: false,
            lineStyle: { color: '#808080', width: 2, type: 'solid' },
            symbol: 'emptyCircle',
            symbolSize: 6,
            showSymbol: true,
            emphasis: { scale: true },
            yAxisIndex: 1,
          },
          {
            name: 'Y轴加减速变化率',
            type: 'line',
            data: [],
            smooth: false,
            lineStyle: { color: '#a9a9a9', width: 2, type: 'solid' },
            symbol: 'emptyCircle',
            symbolSize: 6,
            showSymbol: true,
            emphasis: { scale: true },
            yAxisIndex: 1,
          },
          {
            name: 'Z轴加减速变化率',
            type: 'line',
            data: [],
            smooth: false,
            lineStyle: { color: '#c0c0c0', width: 2, type: 'solid' },
            symbol: 'emptyCircle',
            symbolSize: 6,
            showSymbol: true,
            emphasis: { scale: true },
            yAxisIndex: 1,
          },
          // 电机电流
          {
            name: 'X轴电机电流',
            type: 'line',
            data: [],
            smooth: false,
            lineStyle: { color: '#ff6347', width: 2, type: 'solid' },
            symbol: 'emptyCircle',
            symbolSize: 6,
            showSymbol: true,
            emphasis: { scale: true },
            yAxisIndex: 1,
          },
          {
            name: 'Y轴电机电流',
            type: 'line',
            data: [],
            smooth: false,
            lineStyle: { color: '#ff6347', width: 2, type: 'dashed' },
            symbol: 'emptyCircle',
            symbolSize: 6,
            showSymbol: true,
            emphasis: { scale: true },
            yAxisIndex: 1,
          },
          {
            name: 'Z轴电机电流',
            type: 'line',
            data: [],
            smooth: false,
            lineStyle: { color: '#ff6347', width: 2, type: 'dotted' },
            symbol: 'emptyCircle',
            symbolSize: 6,
            showSymbol: true,
            emphasis: { scale: true },
            yAxisIndex: 1,
          },
          // 电机扭矩
          {
            name: 'X轴电机扭矩',
            type: 'line',
            data: [],
            smooth: false,
            lineStyle: { color: '#4682b4', width: 2, type: 'solid' },
            symbol: 'emptyCircle',
            symbolSize: 6,
            showSymbol: true,
            emphasis: { scale: true },
            yAxisIndex: 1,
          },
          {
            name: 'Y轴电机扭矩',
            type: 'line',
            data: [],
            smooth: false,
            lineStyle: { color: '#4682b4', width: 2, type: 'dashed' },
            symbol: 'emptyCircle',
            symbolSize: 6,
            showSymbol: true,
            emphasis: { scale: true },
            yAxisIndex: 1,
          },
          {
            name: 'Z轴电机扭矩',
            type: 'line',
            data: [],
            smooth: false,
            lineStyle: { color: '#4682b4', width: 2, type: 'dotted' },
            symbol: 'emptyCircle',
            symbolSize: 6,
            showSymbol: true,
            emphasis: { scale: true },
            yAxisIndex: 1,
          },
          // 温度数据
          {
            name: 'X轴温度',
            type: 'line',
            data: [],
            smooth: false,
            lineStyle: { color: '#ff4500', width: 2, type: 'solid' },
            symbol: 'emptyCircle',
            symbolSize: 6,
            showSymbol: true,
            emphasis: { scale: true },
            yAxisIndex: 1,
          },
          {
            name: 'Y轴温度',
            type: 'line',
            data: [],
            smooth: false,
            lineStyle: { color: '#ff6347', width: 2, type: 'solid' },
            symbol: 'emptyCircle',
            symbolSize: 6,
            showSymbol: true,
            emphasis: { scale: true },
            yAxisIndex: 1,
          },
          {
            name: 'Z轴温度',
            type: 'line',
            data: [],
            smooth: false,
            lineStyle: { color: '#ff7f50', width: 2, type: 'solid' },
            symbol: 'emptyCircle',
            symbolSize: 6,
            showSymbol: true,
            emphasis: { scale: true },
            yAxisIndex: 1,
          },
          // 隐藏的占位系列，确保右侧Y轴始终存在
          {
            name: '_placeholder_right_axis',
            type: 'line',
            data: [0, 0], // 最小数据点
            yAxisIndex: 1,
            showSymbol: false,
            lineStyle: {
              color: 'transparent',
              width: 0,
            },
            itemStyle: {
              color: 'transparent',
            },
            silent: true, // 不响应鼠标事件
            legendHoverLink: false, // 不与图例交互
          },
        ],
        backgroundColor: 'transparent',
        animation: true,
        animationDuration: 300,
        dataZoom: [
          {
            type: 'inside',
            xAxisIndex: 0,
            filterMode: 'filter',
            start: 70, // 显示最后30%的数据
            end: 100, // 到最新数据
            zoomLock: false,
            moveOnMouseMove: true,
            moveOnMouseWheel: true,
          },
        ],
      };

      chartInstance.setOption(option);

      // 窗口resize事件监听
      window.addEventListener('resize', () => {
        if (chartInstance) {
          chartInstance.resize();
        }
      });
    });
  };

  // 更新历史数据
  const updateHistoryData = () => {
    // 保留最近50个数据点，增加数据密度
    const maxDataPoints = 50;

    // 添加当前时间标签
    const now = new Date().toLocaleTimeString();
    historyData.value.timeLabels.push(now);
    if (historyData.value.timeLabels.length > maxDataPoints) {
      historyData.value.timeLabels.shift();
    }

    // 移除数据填充逻辑，让图表自然适应数据范围

    // 更新X轴数据
    historyData.value.x.position.push(parseFloat(tableData.value[0].ActPosition) || 0);
    historyData.value.x.speed.push(parseFloat(tableData.value[0].ActSpeed) || 0);
    historyData.value.x.setVelocity.push(parseFloat(tableData.value[0].setVelocity) || 0);
    historyData.value.x.acceleration.push(parseFloat(tableData.value[0].setAcc) || 0);
    historyData.value.x.deceleration.push(parseFloat(tableData.value[0].setDec) || 0);
    historyData.value.x.accDecRate.push(parseFloat(tableData.value[0].setAcc_Dec) || 0);
    historyData.value.x.current.push(parseFloat(tableData.value[0].motorCurrent) || 0);
    historyData.value.x.torque.push(parseFloat(tableData.value[0].motorTorque) || 0);
    historyData.value.x.temperature.push(parseFloat(tableData.value[0].motorTem) || 0);

    // 更新Y轴数据
    historyData.value.y.position.push(parseFloat(tableData.value[1].ActPosition) || 0);
    historyData.value.y.speed.push(parseFloat(tableData.value[1].ActSpeed) || 0);
    historyData.value.y.setVelocity.push(parseFloat(tableData.value[1].setVelocity) || 0);
    historyData.value.y.acceleration.push(parseFloat(tableData.value[1].setAcc) || 0);
    historyData.value.y.deceleration.push(parseFloat(tableData.value[1].setDec) || 0);
    historyData.value.y.accDecRate.push(parseFloat(tableData.value[1].setAcc_Dec) || 0);
    historyData.value.y.current.push(parseFloat(tableData.value[1].motorCurrent) || 0);
    historyData.value.y.torque.push(parseFloat(tableData.value[1].motorTorque) || 0);
    historyData.value.y.temperature.push(parseFloat(tableData.value[1].motorTem) || 0);

    // 更新Z轴数据
    historyData.value.z.position.push(parseFloat(tableData.value[2].ActPosition) || 0);
    historyData.value.z.speed.push(parseFloat(tableData.value[2].ActSpeed) || 0);
    historyData.value.z.setVelocity.push(parseFloat(tableData.value[2].setVelocity) || 0);
    historyData.value.z.acceleration.push(parseFloat(tableData.value[2].setAcc) || 0);
    historyData.value.z.deceleration.push(parseFloat(tableData.value[2].setDec) || 0);
    historyData.value.z.accDecRate.push(parseFloat(tableData.value[2].setAcc_Dec) || 0);
    historyData.value.z.current.push(parseFloat(tableData.value[2].motorCurrent) || 0);
    historyData.value.z.torque.push(parseFloat(tableData.value[2].motorTorque) || 0);
    historyData.value.z.temperature.push(parseFloat(tableData.value[2].motorTem) || 0);

    // 超过最大数据点限制时移除最早的数据
    if (historyData.value.x.position.length > maxDataPoints) {
      // X轴数据清理
      historyData.value.x.position.shift();
      historyData.value.x.speed.shift();
      historyData.value.x.setVelocity.shift();
      historyData.value.x.acceleration.shift();
      historyData.value.x.deceleration.shift();
      historyData.value.x.accDecRate.shift();
      historyData.value.x.current.shift();
      historyData.value.x.torque.shift();
      historyData.value.x.temperature.shift();

      // Y轴数据清理
      historyData.value.y.position.shift();
      historyData.value.y.speed.shift();
      historyData.value.y.setVelocity.shift();
      historyData.value.y.acceleration.shift();
      historyData.value.y.deceleration.shift();
      historyData.value.y.accDecRate.shift();
      historyData.value.y.current.shift();
      historyData.value.y.torque.shift();
      historyData.value.y.temperature.shift();

      // Z轴数据清理
      historyData.value.z.position.shift();
      historyData.value.z.speed.shift();
      historyData.value.z.setVelocity.shift();
      historyData.value.z.acceleration.shift();
      historyData.value.z.deceleration.shift();
      historyData.value.z.accDecRate.shift();
      historyData.value.z.current.shift();
      historyData.value.z.torque.shift();
      historyData.value.z.temperature.shift();
    }

    // 更新图表显示
    updateChart();
  };

  // 更新图表数据
  const updateChart = () => {
    if (!chartInstance) return;

    const dataLength = historyData.value.timeLabels.length;
    let startPercent = 0;
    let endPercent = 100;

    // 动态调整显示窗口：总是显示最新的15个数据点，确保线条分布均匀
    if (dataLength > 15) {
      startPercent = Math.max(0, ((dataLength - 15) / dataLength) * 100);
      endPercent = 100;
    } else if (dataLength > 5) {
      // 如果数据点较少，稍微调整窗口让线条更分散
      startPercent = 0;
      endPercent = 100;
    }

    chartInstance.setOption({
      xAxis: {
        data: historyData.value.timeLabels,
      },
      dataZoom: [
        {
          type: 'inside',
          xAxisIndex: 0,
          start: startPercent,
          end: endPercent,
          filterMode: 'filter',
        },
      ],
      series: [
        // 位置数据
        { name: 'X轴位置', data: historyData.value.x.position },
        { name: 'Y轴位置', data: historyData.value.y.position },
        { name: 'Z轴位置', data: historyData.value.z.position },
        // 速度数据
        { name: 'X轴速度', data: historyData.value.x.speed },
        { name: 'Y轴速度', data: historyData.value.y.speed },
        { name: 'Z轴速度', data: historyData.value.z.speed },
        // 设定速度
        { name: 'X轴设定速度', data: historyData.value.x.setVelocity },
        { name: 'Y轴设定速度', data: historyData.value.y.setVelocity },
        { name: 'Z轴设定速度', data: historyData.value.z.setVelocity },
        // 加速度
        { name: 'X轴加速度', data: historyData.value.x.acceleration },
        { name: 'Y轴加速度', data: historyData.value.y.acceleration },
        { name: 'Z轴加速度', data: historyData.value.z.acceleration },
        // 减速度
        { name: 'X轴减速度', data: historyData.value.x.deceleration },
        { name: 'Y轴减速度', data: historyData.value.y.deceleration },
        { name: 'Z轴减速度', data: historyData.value.z.deceleration },
        // 加减速变化率
        { name: 'X轴加减速变化率', data: historyData.value.x.accDecRate },
        { name: 'Y轴加减速变化率', data: historyData.value.y.accDecRate },
        { name: 'Z轴加减速变化率', data: historyData.value.z.accDecRate },
        // 电机电流
        { name: 'X轴电机电流', data: historyData.value.x.current },
        { name: 'Y轴电机电流', data: historyData.value.y.current },
        { name: 'Z轴电机电流', data: historyData.value.z.current },
        // 电机扭矩
        { name: 'X轴电机扭矩', data: historyData.value.x.torque },
        { name: 'Y轴电机扭矩', data: historyData.value.y.torque },
        { name: 'Z轴电机扭矩', data: historyData.value.z.torque },
        // 温度数据
        { name: 'X轴温度', data: historyData.value.x.temperature },
        { name: 'Y轴温度', data: historyData.value.y.temperature },
        { name: 'Z轴温度', data: historyData.value.z.temperature },
      ],
    });
  };

  // 初始化自定义滚动条
  const initScrollbar = () => {
    nextTick(() => {
      const container = document.querySelector('.main-scroll-container');
      const content = document.querySelector('.scroll-content');
      const scrollbarEl = scrollbar.value;
      const thumb = scrollbarThumb.value;

      if (!container || !content || !scrollbarEl || !thumb) return;

      // 计算滚动条高度
      const updateScrollbar = () => {
        const containerHeight = container.clientHeight;
        const contentHeight = content.scrollHeight;

        // 只有内容高度超过容器高度时才显示滚动条
        if (contentHeight <= containerHeight) {
          scrollbarEl.style.display = 'none';
          return;
        }

        scrollbarEl.style.display = 'block';
        // 计算滚动条 thumb 高度
        const thumbHeight = Math.max(50, (containerHeight / contentHeight) * containerHeight);
        thumb.style.height = `${thumbHeight}px`;
      };

      // 滚动事件处理
      const handleScroll = () => {
        const containerHeight = container.clientHeight;
        const contentHeight = content.scrollHeight;
        const scrollTop = content.scrollTop;

        // 计算 thumb 位置
        const thumbTop =
          (scrollTop / (contentHeight - containerHeight)) * (containerHeight - thumb.offsetHeight);
        thumb.style.top = `${thumbTop}px`;
      };

      // 鼠标拖动滚动条
      let isDragging = false;
      let startY = 0;
      let startScrollTop = 0;

      const handleMouseDown = (e) => {
        isDragging = true;
        startY = e.clientY;
        startScrollTop = content.scrollTop;
        thumb.classList.add('dragging');
        document.body.style.userSelect = 'none';
      };

      const handleMouseMove = (e) => {
        if (!isDragging) return;
        const deltaY = e.clientY - startY;
        const containerHeight = container.clientHeight;
        const contentHeight = content.scrollHeight;
        const thumbHeight = thumb.offsetHeight;

        // 计算新的滚动位置
        const scrollRatio = deltaY / (containerHeight - thumbHeight);
        const newScrollTop = startScrollTop + scrollRatio * (contentHeight - containerHeight);

        content.scrollTop = newScrollTop;
      };

      const handleMouseUp = () => {
        isDragging = false;
        thumb.classList.remove('dragging');
        document.body.style.userSelect = '';
      };

      // 绑定事件
      content.addEventListener('scroll', handleScroll);
      window.addEventListener('resize', updateScrollbar);
      thumb.addEventListener('mousedown', handleMouseDown);
      document.addEventListener('mousemove', handleMouseMove);
      document.addEventListener('mouseup', handleMouseUp);

      // 初始化
      updateScrollbar();
      handleScroll();

      // 清理函数
      return () => {
        content.removeEventListener('scroll', handleScroll);
        window.removeEventListener('resize', updateScrollbar);
        thumb.removeEventListener('mousedown', handleMouseDown);
        document.removeEventListener('mousemove', handleMouseMove);
        document.removeEventListener('mouseup', handleMouseUp);
      };
    });
  };

  // WebSocket初始化
  const initWebSocket = () => {
    const websocketStore = useWebsocketStoreWithOut();
    const wsUrl = websocketStore.getBackendWsUrl;
    const socket = new WebSocket(wsUrl);

    socket.onopen = () => {
      console.log('WebSocket连接已建立');
      isConnected.value = true;

      // 发送订阅命令
      const subscriptionCmd = {
        tsSubCmds: [
          {
            entityType: 'DEVICE',
            entityId: deviceId,
            scope: 'LATEST_TELEMETRY',
            cmdId: 10,
          },
        ],
        historyCmds: [],
        attrSubCmds: [],
      };

      socket.send(JSON.stringify(subscriptionCmd));
    };

    socket.onmessage = (event) => {
      try {
        const telemetryUpdate = JSON.parse(event.data);

        if (telemetryUpdate.subscriptionId === 10 && telemetryUpdate.data) {
          const telemetry = telemetryUpdate.data;
          updateTelemetryData(telemetry);
          lastUpdateTime.value = new Date().toLocaleTimeString();
        }
      } catch (error) {
        console.error('处理遥测数据错误:', error);
      }
    };

    socket.onerror = (error) => {
      console.error('WebSocket错误:', error);
      isConnected.value = false;
      // ElMessage.error('连接遥测数据失败，将切换到轮询模式');

      // 降级到HTTP轮询
      startHttpPolling();
    };

    socket.onclose = () => {
      isConnected.value = false;
      console.log('WebSocket连接已关闭');
      // 尝试重新连接
      setTimeout(() => {
        initWebSocket();
      }, 5000);
    };

    return socket;
  };

  // HTTP轮询获取数据
  const startHttpPolling = () => {
    if (timer) clearInterval(timer);

    const keys =
      'axisX_ActPosition,axisX_ActSpeed,axisX_setVelocity,axisX_setAcc,axisX_setDec,axisX_setAcc_Dec,axisX_axisSignal,axisX_motorCurrent,axisX_motorTorque,axisX_motorTem,axisX_faultCode,axisY_ActPosition,axisY_ActSpeed,axisY_setVelocity,axisY_setAcc,axisY_setDec,axisY_setAcc_Dec,axisY_axisSignal,axisY_motorCurrent,axisY_motorTorque,axisY_motorTem,axisY_faultCode,axisZ_ActPosition,axisZ_ActSpeed,axisZ_setVelocity,axisZ_setAcc,axisZ_setDec,axisZ_setAcc_Dec,axisZ_axisSignal,axisZ_motorCurrent,axisZ_motorTorque,axisZ_motorTem,axisZ_faultCode';

    timer = setInterval(() => {
      getLatestTelemetry({
        entityType: 'DEVICE',
        entityId: deviceId,
        keys: keys,
      })
        .then((data) => {
          updateTelemetryData(data);
          isConnected.value = true;
          lastUpdateTime.value = new Date().toLocaleTimeString();
        })
        .catch((error) => {
          console.error('获取遥测数据失败:', error);
          isConnected.value = false;
        });
    }, pollingInterval);
  };

  // 更新表格数据
  const updateTelemetryData = (telemetry) => {
    // 更新X轴数据
    if (telemetry.axisX_ActPosition)
      tableData.value[0].ActPosition = getLatestValue(telemetry.axisX_ActPosition);
    if (telemetry.axisX_setVelocity)
      tableData.value[0].setVelocity = getLatestValue(telemetry.axisX_setVelocity);
    if (telemetry.axisX_ActSpeed)
      tableData.value[0].ActSpeed = getLatestValue(telemetry.axisX_ActSpeed);
    if (telemetry.axisX_setAcc) tableData.value[0].setAcc = getLatestValue(telemetry.axisX_setAcc);
    if (telemetry.axisX_setDec) tableData.value[0].setDec = getLatestValue(telemetry.axisX_setDec);
    if (telemetry.axisX_setAcc_Dec)
      tableData.value[0].setAcc_Dec = getLatestValue(telemetry.axisX_setAcc_Dec);
    if (telemetry.axisX_axisSignal)
      tableData.value[0].axisSignal = getLatestValue(telemetry.axisX_axisSignal);
    if (telemetry.axisX_motorCurrent)
      tableData.value[0].motorCurrent = getLatestValue(telemetry.axisX_motorCurrent);
    if (telemetry.axisX_motorTorque)
      tableData.value[0].motorTorque = getLatestValue(telemetry.axisX_motorTorque);
    if (telemetry.axisX_motorTem)
      tableData.value[0].motorTem = getLatestValue(telemetry.axisX_motorTem);
    if (telemetry.axisX_faultCode)
      tableData.value[0].faultCode = getLatestValue(telemetry.axisX_faultCode);

    // 更新Y轴数据
    if (telemetry.axisY_ActPosition)
      tableData.value[1].ActPosition = getLatestValue(telemetry.axisY_ActPosition);
    if (telemetry.axisY_setVelocity)
      tableData.value[1].setVelocity = getLatestValue(telemetry.axisY_setVelocity);
    if (telemetry.axisY_ActSpeed)
      tableData.value[1].ActSpeed = getLatestValue(telemetry.axisY_ActSpeed);
    if (telemetry.axisY_setAcc) tableData.value[1].setAcc = getLatestValue(telemetry.axisY_setAcc);
    if (telemetry.axisY_setDec) tableData.value[1].setDec = getLatestValue(telemetry.axisY_setDec);
    if (telemetry.axisY_setAcc_Dec)
      tableData.value[1].setAcc_Dec = getLatestValue(telemetry.axisY_setAcc_Dec);
    if (telemetry.axisY_axisSignal)
      tableData.value[1].axisSignal = getLatestValue(telemetry.axisY_axisSignal);
    if (telemetry.axisY_motorCurrent)
      tableData.value[1].motorCurrent = getLatestValue(telemetry.axisY_motorCurrent);
    if (telemetry.axisY_motorTorque)
      tableData.value[1].motorTorque = getLatestValue(telemetry.axisY_motorTorque);
    if (telemetry.axisY_motorTem)
      tableData.value[1].motorTem = getLatestValue(telemetry.axisY_motorTem);
    if (telemetry.axisY_faultCode)
      tableData.value[1].faultCode = getLatestValue(telemetry.axisY_faultCode);

    // 更新Z轴数据
    if (telemetry.axisZ_ActPosition)
      tableData.value[2].ActPosition = getLatestValue(telemetry.axisZ_ActPosition);
    if (telemetry.axisZ_setVelocity)
      tableData.value[2].setVelocity = getLatestValue(telemetry.axisZ_setVelocity);
    if (telemetry.axisZ_ActSpeed)
      tableData.value[2].ActSpeed = getLatestValue(telemetry.axisZ_ActSpeed);
    if (telemetry.axisZ_setAcc) tableData.value[2].setAcc = getLatestValue(telemetry.axisZ_setAcc);
    if (telemetry.axisZ_setDec) tableData.value[2].setDec = getLatestValue(telemetry.axisZ_setDec);
    if (telemetry.axisZ_setAcc_Dec)
      tableData.value[2].setAcc_Dec = getLatestValue(telemetry.axisZ_setAcc_Dec);
    if (telemetry.axisZ_axisSignal)
      tableData.value[2].axisSignal = getLatestValue(telemetry.axisZ_axisSignal);
    if (telemetry.axisZ_motorCurrent)
      tableData.value[2].motorCurrent = getLatestValue(telemetry.axisZ_motorCurrent);
    if (telemetry.axisZ_motorTorque)
      tableData.value[2].motorTorque = getLatestValue(telemetry.axisZ_motorTorque);
    if (telemetry.axisZ_motorTem)
      tableData.value[2].motorTem = getLatestValue(telemetry.axisZ_motorTem);
    if (telemetry.axisZ_faultCode)
      tableData.value[2].faultCode = getLatestValue(telemetry.axisZ_faultCode);

    // 更新图表数据
    updateHistoryData();
  };

  // 从遥测数据中提取最新值
  const getLatestValue = (data) => {
    // 处理WebSocket数据格式 [ts, value]
    if (Array.isArray(data) && data.length > 0 && Array.isArray(data[0])) {
      return data[0][1];
    }
    // 处理HTTP请求数据格式
    if (Array.isArray(data) && data.length > 0 && data[0].value !== undefined) {
      return data[0].value;
    }
    // 直接返回值
    return data;
  };

  // 窗口大小变化时重绘图表
  const handleResize = () => {
    if (chartInstance) {
      chartInstance.resize();
    }
  };

  // 组件生命周期
  let socket = null;
  let cleanupScrollbar = null;

  onMounted(() => {
    socket = initWebSocket();
    initChart();
    cleanupScrollbar = initScrollbar();
    window.addEventListener('resize', handleResize);
  });

  onUnmounted(() => {
    // 清理资源
    if (socket) {
      socket.close();
    }
    if (timer) {
      clearInterval(timer);
    }
    if (chartInstance) {
      chartInstance.dispose();
    }
    if (cleanupScrollbar) {
      cleanupScrollbar();
    }
    window.removeEventListener('resize', handleResize);
  });
</script>

<style scoped>
  .dashboard-container {
    background: rgba(255, 255, 255, 0.08);
    padding: 1vw;
    color: rgba(255, 255, 255, 0.9);
    height: 100%;
    overflow: hidden;
    box-sizing: border-box;
    margin: 0;
    display: flex;
    flex-direction: column;
  }

  .panel-title {
    margin: 0 0 1vw 0;
    font-size: 1.2vw;
    color: rgba(255, 255, 255, 0.95);
    text-shadow: 0 0.05vw 0.15vw rgba(0, 0, 0, 0.1);
  }

  /* 主滚动容器 - 包含内容和滚动条 */
  .main-scroll-container {
    position: relative;
    width: 100%;
    flex: 1; /* 使用flex-grow填满剩余空间 */
    overflow: hidden;
  }

  /* 滚动内容区域 */
  .scroll-content {
    width: calc(100% - 0.6vw); /* 留出滚动条空间 */
    height: 100%;
    overflow-y: scroll;
    scrollbar-width: none; /* 隐藏原生滚动条 */
  }

  .scroll-content::-webkit-scrollbar {
    display: none; /* 隐藏WebKit浏览器原生滚动条 */
  }

  /* 自定义左侧滚动条 */
  .custom-scrollbar {
    position: absolute;
    left: 0;
    top: 0;
    width: 0.4vw;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.1);
    border-radius: 0.2vw;
    z-index: 10;
    display: none; /* 默认隐藏，内容超出时显示 */
  }

  .scrollbar-thumb {
    position: absolute;
    left: 0;
    width: 100%;
    background-color: rgba(100, 100, 100, 0.6);
    border-radius: 0.2vw;
    cursor: pointer;
    transition: background-color 0.2s ease;
  }

  .scrollbar-thumb:hover {
    background-color: rgba(150, 150, 150, 0.7);
  }

  .scrollbar-thumb.dragging {
    background-color: rgba(200, 200, 200, 0.8);
  }

  .monitoring-card {
    background: rgba(0, 0, 0, 0.15);
    border: 0.05vw solid rgba(255, 255, 255, 0.1);
    margin: 0;
    backdrop-filter: blur(0.25vw);
    padding: 0.8vw;
  }

  /* 分隔线 */
  .separator {
    height: 0.05vw;
    background: rgba(255, 255, 255, 0.1);
    margin: 1vw 0;
  }

  /* 表格样式 */
  :deep(.el-table) {
    --el-table-border-color: rgba(255, 255, 255, 0.1);
    --el-table-bg-color: rgba(0, 46, 93, 0.6);
    --el-table-tr-bg-color: rgba(0, 46, 93, 0.6);
    --el-table-text-color: rgba(255, 255, 255, 0.9);
    border: 0.05vw solid rgba(255, 255, 255, 0.1);
    margin-bottom: 0.8vw;
  }

  :deep(.el-table th) {
    background: rgba(0, 46, 93, 0.8);
    color: rgba(255, 255, 255, 0.95);
  }

  :deep(.el-table__row:hover > td) {
    background-color: rgba(255, 255, 255, 0.1) !important;
  }

  /* 图表容器样式 */
  .chart-container {
    background: rgba(138, 139, 142, 0.5);
    border-radius: 1vw;
    padding: 0.5vw 1vw;
    margin-top: 1vh;
    height: 35vh;
  }

  .chart-wrapper {
    width: 100%;
    height: 100%;
  }

  /* 卡片内边距调整 */
  :deep(.el-card__body) {
    padding: 0;
  }
</style>
